// 桥接模式 -------------
// 未采用设计模式的代码
let book1 = {
  category: '图书',
  name: '西游记',
  oriPrice: 13,
}
let book2 = {
  category: '图书',
  name: '红楼梦',
  oriPrice: 12
}
let mobile1 = {
  category: '手机',
  name: '小米6',
  oriPrice: 1500
}
let mobile2 = {
  category: '手机',
  name: 'iPhone8',
  oriPrice: 6000
}

// 打折策略
function onSaleStrategy(price) {
  return price * 0.8
}

// 返现策略
function returnCashStrategy(price) {
  return price >= 100 ? (price - 50) : price
}

// 获得商品促销后总价
function getTotalPrice(goodsArr) {
  let totalPrice = 0
  goodsArr.forEach(g => {
    if (g.category === '手机') {
      // 先打折再返现
      totalPrice += returnCashStrategy(onSaleStrategy(g.oriPrice))
    } else if (g.category === '图书') {
      // 打折
      totalPrice += onSaleStrategy(g.oriPrice)
    } else {
      totalPrice += g.oriPrice
    }
  })
  return totalPrice
}

getTotalPrice([book1, mobile1])

// 采用桥接模式的代码
class Goods {
  constructor(category, name, oriPrice, promotions) {
    this.category = category
    this.name = name
    this.oriPrice = oriPrice
    this.promotions = promotions
  }

  getPrice() {
    let price = this.oriPrice
    this.promotions.forEach(p => {
      price = p(price)
    });
    return price
  }
}
class Book extends Goods {
  constructor(name, oriPrice, promotions) {
    super("图书", name, oriPrice, promotions)
  }
}
class Mobile extends Goods {
  constructor(name, oriPrice, promotions) {
    super("手机", name, oriPrice, promotions)
  }
}
class Clothing extends Goods {
  constructor(name, oriPrice, promotions) {
    super("服装", name, oriPrice, promotions)
  }
}

// 打折策略
function onSaleStrategy(price) {
  return price * 0.8
}

// 满100返50策略
function returnCashStrategy(price) {
  return price >= 100 ? (price - 50) : price
}

// 每满100返现50策略
function returnCash2Strategy(price) {
  return price - parseInt(price / 100) * 50
}

// 获得商品促销后总价
function getTotalPrice(goodsArr) {
  let totalPrice = 0
  goodsArr.forEach(g => {
    totalPrice += g.getPrice()
  })
  return totalPrice
}

const totalPrice = getTotalPrice([
  new Book("西游记", 13, [onSaleStrategy]),
  new Book("小米6", 1500, [onSaleStrategy, returnCashStrategy]),
  new Clothing("裙子", 500, [onSaleStrategy, returnCash2Strategy])
])
